import 'package:flutter/material.dart';
import '../theme/app_theme.dart';
import '../models/folder_model.dart';

/**
 * 可拖拽的文件夹项组件
 * 支持拖拽排序和层级关系
 */
class DraggableFolderItem extends StatefulWidget {
  final FolderModel folder;
  final bool isSelected;
  final int depth;
  final Function(FolderModel) onTap;
  final Function(FolderModel, FolderModel) onDrop;
  final Function(FolderModel) onExpansionChanged;
  final VoidCallback? onEdit;
  final VoidCallback? onDelete;

  const DraggableFolderItem({
    super.key,
    required this.folder,
    required this.isSelected,
    this.depth = 0,
    required this.onTap,
    required this.onDrop,
    required this.onExpansionChanged,
    this.onEdit,
    this.onDelete,
  });

  @override
  State<DraggableFolderItem> createState() => _DraggableFolderItemState();
}

class _DraggableFolderItemState extends State<DraggableFolderItem>
    with SingleTickerProviderStateMixin {
  bool _isDragTarget = false;
  late AnimationController _animationController;
  late Animation<double> _scaleAnimation;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 200),
      vsync: this,
    );
    _scaleAnimation = Tween<double>(
      begin: 1.0,
      end: 0.95,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: Curves.easeInOut,
    ));
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  /**
   * 构建文件夹图标
   */
  Widget _buildFolderIcon() {
    IconData iconData;
    if (widget.folder.childrenIds.isNotEmpty) {
      iconData = widget.folder.isExpanded ? Icons.folder_open : Icons.folder;
    } else {
      iconData = widget.folder.icon ?? Icons.folder_outlined;
    }

    return Icon(
      iconData,
      size: 20,
      color: widget.isSelected 
          ? AppTheme.primaryColor 
          : (widget.folder.color ?? AppTheme.textSecondary),
    );
  }

  /**
   * 构建文件夹标题
   */
  Widget _buildFolderTitle() {
    return Expanded(
      child: Text(
        widget.folder.name,
        style: TextStyle(
          fontSize: 14,
          fontWeight: widget.isSelected ? FontWeight.w500 : FontWeight.normal,
          color: widget.isSelected ? AppTheme.primaryColor : AppTheme.textPrimary,
        ),
        overflow: TextOverflow.ellipsis,
      ),
    );
  }

  /**
   * 构建展开/收起按钮
   */
  Widget? _buildExpansionButton() {
    if (widget.folder.childrenIds.isEmpty) return null;

    return GestureDetector(
      onTap: () {
        final updatedFolder = widget.folder.copyWith(
          isExpanded: !widget.folder.isExpanded,
        );
        widget.onExpansionChanged(updatedFolder);
      },
      child: Icon(
        widget.folder.isExpanded ? Icons.expand_less : Icons.expand_more,
        size: 16,
        color: AppTheme.textSecondary,
      ),
    );
  }

  /**
   * 构建右键菜单
   */
  Widget _buildContextMenu() {
    return PopupMenuButton<String>(
      icon: Icon(
        Icons.more_vert,
        size: 16,
        color: AppTheme.textSecondary,
      ),
      itemBuilder: (context) => [
        const PopupMenuItem(
          value: 'edit',
          child: Row(
            children: [
              Icon(Icons.edit, size: 16),
              SizedBox(width: 8),
              Text('重命名'),
            ],
          ),
        ),
        const PopupMenuItem(
          value: 'delete',
          child: Row(
            children: [
              Icon(Icons.delete, size: 16, color: Colors.red),
              SizedBox(width: 8),
              Text('删除', style: TextStyle(color: Colors.red)),
            ],
          ),
        ),
      ],
      onSelected: (value) {
        switch (value) {
          case 'edit':
            widget.onEdit?.call();
            break;
          case 'delete':
            widget.onDelete?.call();
            break;
        }
      },
    );
  }

  /**
   * 构建文件夹内容
   */
  Widget _buildFolderContent() {
    return Container(
      margin: EdgeInsets.only(
        left: widget.depth * 16.0 + 8,
        right: 8,
        top: 2,
        bottom: 2,
      ),
      decoration: BoxDecoration(
        color: _isDragTarget 
            ? AppTheme.primaryColor.withOpacity(0.1)
            : (widget.isSelected ? AppTheme.sidebarSelected : Colors.transparent),
        borderRadius: BorderRadius.circular(8),
        border: _isDragTarget 
            ? Border.all(color: AppTheme.primaryColor, width: 2)
            : null,
      ),
      child: ListTile(
        leading: _buildFolderIcon(),
        title: _buildFolderTitle(),
        trailing: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            if (widget.folder.childrenIds.isNotEmpty) ...[
              Text(
                widget.folder.childrenIds.length.toString(),
                style: TextStyle(
                  fontSize: 12,
                  color: widget.isSelected 
                      ? AppTheme.primaryColor 
                      : AppTheme.textSecondary,
                ),
              ),
              const SizedBox(width: 4),
            ],
            if (_buildExpansionButton() != null) _buildExpansionButton()!,
            _buildContextMenu(),
          ],
        ),
        contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
        onTap: () => widget.onTap(widget.folder),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _scaleAnimation,
      builder: (context, child) {
        return Transform.scale(
          scale: _scaleAnimation.value,
          child: Draggable<FolderModel>(
            data: widget.folder,
            feedback: Material(
              elevation: 8,
              borderRadius: BorderRadius.circular(8),
              child: Container(
                width: 200,
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                  color: AppTheme.sidebarBackground,
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    _buildFolderIcon(),
                    const SizedBox(width: 8),
                    Text(
                      widget.folder.name,
                      style: const TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ],
                ),
              ),
            ),
            childWhenDragging: Opacity(
              opacity: 0.5,
              child: _buildFolderContent(),
            ),
            onDragStarted: () {
              _animationController.forward();
            },
            onDragEnd: (details) {
              _animationController.reverse();
            },
            child: DragTarget<FolderModel>(
              onWillAccept: (data) {
                if (data == null || data.id == widget.folder.id) return false;
                
                // 检查是否可以拖拽到当前文件夹
                return _canAcceptDrop(data);
              },
              onAccept: (data) {
                widget.onDrop(data, widget.folder);
                setState(() {
                  _isDragTarget = false;
                });
              },
              onMove: (details) {
                if (!_isDragTarget) {
                  setState(() {
                    _isDragTarget = true;
                  });
                }
              },
              onLeave: (data) {
                setState(() {
                  _isDragTarget = false;
                });
              },
              builder: (context, candidateData, rejectedData) {
                return _buildFolderContent();
              },
            ),
          ),
        );
      },
    );
  }

  /**
   * 检查是否可以接受拖拽
   */
  bool _canAcceptDrop(FolderModel draggedFolder) {
    // 不能拖拽到自己
    if (draggedFolder.id == widget.folder.id) return false;
    
    // 不能拖拽到自己的子文件夹（防止循环引用）
    if (_isDescendantOf(widget.folder, draggedFolder)) return false;
    
    return true;
  }

  /**
   * 检查目标文件夹是否是拖拽文件夹的后代
   */
  bool _isDescendantOf(FolderModel target, FolderModel ancestor) {
    if (target.parentId == ancestor.id) return true;
    
    // 这里需要递归检查，但由于我们只有ID，需要从外部传入完整的文件夹树
    // 暂时简化处理
    return false;
  }
}